package com.javandad.app.server.servlet;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.javandad.app.client.toppanel.TopPanelService;
import com.javandad.app.server.db.DatabaseManager;
import com.javandad.app.server.db.PMFSingleton;
import com.javandad.app.server.mail.MailHandler;
import com.javandad.app.server.mail.entity.FInvitationMail;
import com.javandad.app.server.mail.entity.MessageMail;
import com.javandad.app.shared.entity.Friendship;
import com.javandad.app.shared.entity.Message;

/**
 * The server side implementation of the RPC service.
 */

public class TopPanelServiceImpl extends RemoteServiceServlet implements
		TopPanelService {
	private static final long serialVersionUID = 9181996541037379837L;

	@Override
	public List<String> getSessionInfo() throws IllegalArgumentException {
		List<String> list = new LinkedList<String>();
		HttpSession session = this.getThreadLocalRequest().getSession();
		list.add((String) session.getAttribute("mode"));
		list.add((String) session.getAttribute("username"));
		return list;
	}

	@Override
	public Boolean addAsFriend(final Friendship friendship)
			throws IllegalArgumentException {
		boolean result = false;
		friendship.setDateOfInvitation(new Date());
		PersistenceManager pm = PMFSingleton.getPM();
		pm.makePersistent(friendship);
		pm.close();
		// Thread t = new Thread(new Runnable(){
		// public void run(){
		MailHandler.sendMail(new FInvitationMail(friendship));
		// }
		// });
		// t.start();
		result = true;
		return result;
	}

	@Override
	public Boolean sendMessage(final Message message)
			throws IllegalArgumentException {
		Boolean result = false;
		message.setDateOfDelivery(new Date());
		PersistenceManager pm = PMFSingleton.getPM();
		pm.makePersistent(message);
		pm.close();

		MailHandler.sendMail(new MessageMail(message));
		result = true;
		return result;
	}

	@Override
	public Integer checkRelationshipStatus(String user1, String user2) {
		int result = -1;
		PersistenceManager pm = PMFSingleton.getPM();
		Friendship friendship = DatabaseManager.getDefaultDatabaseManager()
				.getFriendship(user1, user2, pm);
		pm.close();
		if (friendship == null)
			result = 0;
		else if (friendship.isConfirmed())
			result = 1;
		else
			result = 2;
		return result;
	}

}
